<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function stock_info_list_page()
{
    @$output = drupal_render(drupal_get_form('stock_info_list_form'));
    return $output;
}


function stock_info_list_form($form, &$form_state)
{
    global $user;
    if (!empty($_GET['distributor_id'])) {
        $form_state['distributor_id'] = $_GET['distributor_id'];
    }
    if (empty($form_state['distributor_id'])) {
    } else {
        $form['#distributor_id'] = $form_state['distributor_id'];
        $res = get_info($form['#distributor_id'], 'distributor');
        $form['#distributor_name'] = $res[0]->distributor_name;
//        $addr_red = get_all_addrname($res[0]->addr_id);
//        $province = $addr_red[0]->province?$addr_red[0]->province:"";
//        $city = $addr_red[0]->city? '  '.$addr_red[0]->city:"";
//        $county = $addr_red[0]->county? '  '.$addr_red[0]->county:"";
//        $town = $addr_red[0]->town? '  '.$addr_red[0]->town:"";
//        $village = $addr_red[0]->village? '  '.$addr_red[0]->village:"";
//        $form['#farmer_addr'] =$province.$city.$county.$town.$village;
    }
    $init_year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : "";
    $init_month = !empty($form_state['values']['month']) ? $form_state['values']['month'] : "";
    _insert_date_selection_form($form, $form_state, 5, $init_year, $init_month);
    $form['sacfvariety'] = _insert_sacfvariety_selection_form(!empty($form_state['values']['sacfvariety']) ? $form_state['values']['sacfvariety'] : '');
    $fields = array(
        '' => '请选择',
        'last_month_stock' => '上月库存量',
        'return_stock' => '回库量',
        'this_month_instock' => '当月进库量',
        'this_month_outstock' => '当月出库量',
        'break this_month_stock' => '当月库量',
        'this_month_sales' => '当月销量',
    );
    numerical_range_search($form, $fields);
//    $form['employee_salesman'] = get_all_salesman();
    if (get_user_role_name($user->uid) === 'administrator') {

    } else {
//        $form['employee_list'] = _insert_loginuser_choose_salesman_selection($user);
    }
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}

function check_month_not_empty($form, &$form_state)
{
    if (empty($form_state['values']['month'])) {
        form_set_error('month', '月 不能为空');
    }
}

function stock_info_list_form_validate($form, &$form_state)
{
}

function data_list_view_page($form = '', &$form_state = '')
{
    global $user;
    $user_info = _get_user_info();
    $output = '';
    $query = db_select('stock_info', 'S')->extend('PagerDefault')->extend('TableSort');//库存表
    $query->join('distributor', 'D', 'S.distributor_id=D.distributor_id');//内连接 成一个表
    $query->join('product_sku', 'V', 'V.product_sku_id=S.sacfvariety_id');//通过distributor addr_id 左联addr 得到地址名称
    $query->join('employee','E','E.employee_id = S.author_uid');
    $query->fields('S');
    $query->addField('V', 'variety_name');
    $query->addField('V', 'proportion');
    $query->addField('V', 'SM');
    $query->fields('D', array('distributor_name','addr_id'));
    $query->fields('E', array('employee_name','juris_id'));

    //条件筛选
    if (!empty($form_state['values']['year'])) {//year查询条件
        $query->condition('S.year', $form_state['values']['year']);
    }
    if (!empty($form_state['values']['month'])) {//month查询条件
        $query->condition('S.month', $form_state['values']['month']);
    }
    if (!empty($form_state['values']['sacfvariety'])) {
        $query->condition('S.sacfvariety_id', $form_state['values']['sacfvariety']);
    }

    salesman_distributor_role_relate_query_info($form_state,$query,'view all stock_info','view own stock_info',"S");

    if (!empty($form_state['values']['employee_list']) && $form_state['values']['employee_list'] != "default") {//查询条件
        if ($form_state['values']['employee_list']) {
            $query->condition('S.author_uid', $form_state['values']['employee_list']);
        }
    }

    if (empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('S.timestamp', 'DESC');
    }

    if (!empty($form_state['values']['field'])) {
        if (!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])) {
            $db_and = db_and();
            $db_and->condition('S.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('S.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($form_state['values']['min_number'])) {
            $query->condition('S.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('S.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }
    if (!empty($form_state['values']['employee_salesman'])) {
        $query->condition('S.author_uid', $form_state['values']['employee_salesman'], '=');
    }
    if (!empty($form_state['distributor_id'])) {
        $query->condition('D.distributor_id', $form_state['distributor_id']);
    }
    $query->limit(variable_get("list_page_item_number", 5));

    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        array('data' => '部门', 'class' => ['essential juris']),
        array('data' => '年份', 'class' => ['integrant essential optional year'], 'field' => 'year'),
        array('data' => '月份', 'class' => [' essential optional month']),
        array('data' => '周', 'class' => [' essential optional week']),
        array('data' => '行政区', 'class' => [' essential optional addr_name']),
        isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ? "" :
            array('data' => '经销商', 'class' => ['essential distributor']),
        array('data' => '化肥品种', 'class' => ['essential sacfvariety']),
        array('data' => '配比', 'class' => 'optional proportion'),
        array('data' => 'SM', 'class' => 'optional SM'),
        array('data' => '上月库存量', 'class' => ['essential break last_month_stock']),
        array('data' => '回库量', 'class' => ['essential break return_stock']),
        array('data' => '当月进库量', 'class' => ['essential break this_month_instock']),
        array('data' => '当月出库量', 'class' => ['essential break this_month_outstock']),
        array('data' => '当月库量', 'class' => ['integrant essential break this_month_stock'], 'field' => 'this_month_stock'),
        array('data' => '当月销量', 'class' => ['essential break this_month_sales']),
        array('data' =>'上报人','class' => ['essential break author']),
        array('data' => '操作', 'class' => ['essential more']),
        array('data' => '克隆', 'class' => ['essential more']),
    );
    $stock_infoInfo = $query->orderByHeader($header)->execute();

    $rows = array();
    //表内容
    $n = 1;
    $user_role_name = get_user_role_name($user->uid);
    foreach ($stock_infoInfo as $row) {
        if (nonghua_user_access('stock_info', 'delete', $row->stock_info_id, $row->author_uid, 0)) {
            $disabled = ' class="listViewTableCheck" ';
        } else {
            $disabled = ' disabled="true" ';
        }
        $addr_name = get_all_addrname($row->addr_id);
        $juris = nonghua_data_load('juris','juris_id',$row->juris_id);
        $rows[] = array(
            array('data' => "<input type='checkbox''.$disabled.' value ='" . $row->stock_info_id . "' name='" . $row->stock_info_id . "'/>", 'class' => 'essential no'),
            array('data' => $juris->juris_name, 'class' => ['essential optional juris_name']),
            array('data' => $row->year, 'class' => ['essential optional year']),
            array('data' => $row->month, 'class' => ['essential optional month']),
            array('data' => $row->week, 'class' => ['essential optional week']),
            array('data' => $addr_name, 'class' => ['essential optional addr_name']),
            isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ? "" :
                array('data' => '<a href="' . base_path() . 'distributor/edit/' . $row->distributor_id . '?distributor_id=' . $row->distributor_id . '" data-toggle="modal" target = "_self">' . $row->distributor_name . '</a>', 'class' => ['essential distributor_name']),
            array('data' => $row->variety_name, 'class' => ['essential sacfvariety']),
            array('data' => $row->proportion, 'class' => 'optional proportion'),
            array('data' => $row->SM, 'class' => 'optional SM'),
            array('data' => $row->last_month_stock, 'class' => ['essential break last_month_stock']),
            array('data' => $row->return_stock, 'class' => ['essential break return_stock']),
            array('data' => $row->this_month_instock, 'class' => ['essential break this_month_instock']),
            array('data' => $row->this_month_outstock, 'class' => ['essential break this_month_outstock']),
            array('data' => $row->this_month_stock, 'class' => ['essential break this_month_stock']),
            array('data' => $row->this_month_sales, 'class' => ['essential break this_month_sales']),
            array('data' => $row->employee_name, 'class' => ['essential break employee_name']),
            isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ?
                array('data' => '<a href="' . base_path() . 'stock_info/edit/' . $row->stock_info_id . '?distributor_id=' . $form_state['distributor_id'] . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more') :
                array('data' => '<a href="' . base_path() . 'stock_info/edit/' . $row->stock_info_id . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
            array('data' => '<a href="'.base_path().'stock_info/clone/' . $row->stock_info_id . '" data-toggle="modal"class="btn" target = "_top">克隆</a>', 'class' => ['essential']),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own stock_info') || user_access('delete all stock_info'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }

    $output .= '<a href="'.base_path().'stock_info/export?sacfvariety=' .$form_state['values']['sacfvariety'].'&year='.$form_state['values']['year'].'&month='.$form_state['values']['month'].'&field='.$form_state['values']['field'].'&min_number='.$form_state['values']['min_number'].'&max_number='.$form_state['values']['max_number'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
    $output .= theme('pager');
    return $output;
}

function stock_info_delete()
{
    ajax_table_delete('stock_info', 'stock_info_id');
}

function stock_info_export(){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S');
    $tableheader = array('部门','行政区','经销商','化肥品种', '配比','SM','年份','月份','周', '上月库存量','回库量', '当月进库量','当月出库量','当月库量', '当月销量', '上报人');
    $data = get_stock_info_data();
    nonghua_php_excel($letter,$tableheader,$data,'库存信息数据');
}

function get_stock_info_data($form = '', &$form_state = ''){
    global $user;
    $query = db_select('stock_info', 'S');//库存表
    $query->join('distributor', 'D', 'S.distributor_id=D.distributor_id');//内连接 成一个表
    $query->join('product_sku', 'V', 'V.product_sku_id=S.sacfvariety_id');//通过distributor addr_id 左联addr 得到地址名称
    $query->join('employee','E','E.employee_id = S.author_uid');
    $query->addField('E', 'juris_id');
    $query->addField('D', 'addr_id');
    $query->addField('D', 'distributor_name');
    $query->addField('V', 'variety_name');
    $query->addField('V', 'proportion');
    $query->addField('V', 'SM');
    $query->fields('S',array('year','month','week','last_month_stock','return_stock','this_month_instock','this_month_outstock','this_month_stock','this_month_sales'));
    $query->addField('E', 'employee_name');
    //条件筛选
    if (!empty($_GET['year'])) {//year查询条件
        $query->condition('S.year',$_GET['year']);
    }
    if (!empty($_GET['month'])) {//month查询条件
        $query->condition('S.month', $_GET['month']);
    }
    if (!empty($_GET['sacfvariety'])) {
        $query->condition('S.sacfvariety_id',$_GET['sacfvariety']);
    }

    salesman_distributor_role_relate_query_info($form_state,$query,'view all stock_info','view own stock_info',"S");

    if (!empty($_GET['employee_list']) && $_GET['employee_list'] != "default") {//查询条件
        if ($_GET['employee_list']) {
            $query->condition('S.author_uid', $_GET['employee_list']);
        }
    }

    if (!empty($_GET['field'])) {
        if (!empty($_GET['min_number']) && !empty($_GET['max_number'])) {
            $db_and = db_and();
            $db_and->condition('S.' . $_GET['field'],$_GET['min_number'], '>');
            $db_and->condition('S.' . $_GET['field'],$_GET['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($_GET['min_number'])) {
            $query->condition('S.' . $_GET['field'], $_GET['min_number'], '>');
        } elseif (!empty($_GET['max_number'])) {
            $query->condition('S.' . $_GET['field'], $_GET['max_number'], '<');
        }
    }
    $stock_infoInfo = $query->execute()->fetchAll();
    foreach($stock_infoInfo as $key=>$val){
        $val->addr_id = get_all_addrname($val->addr_id);
        $val->juris_id = nonghua_data_load('juris','juris_id',$val->juris_id)->juris_name;
    }
    return $stock_infoInfo;
}